/**
 * 模块状态管理 Store
 * 基于 Pinia 的模块状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { moduleManager } from '@/modules/dynamic/ModuleManager'
import type { 
  DynamicModule, 
  ModuleLoadState, 
  ModulePerformanceMetrics,
  ModuleErrorInfo,
  ModuleConfig
} from '@/modules/dynamic/types'

export const useModuleStore = defineStore('module', () => {
  // 状态定义
  const modules = ref<DynamicModule[]>([])
  const loadedModules = ref<DynamicModule[]>([])
  const enabledModules = ref<DynamicModule[]>([])
  const loadingModules = ref<Set<string>>(new Set())
  const errorModules = ref<Map<string, string>>(new Map())
  const performanceMetrics = ref<Map<string, ModulePerformanceMetrics>>(new Map())
  const errorHistory = ref<Map<string, ModuleErrorInfo[]>>(new Map())
  const moduleConfigs = ref<Map<string, ModuleConfig>>(new Map())

  // 计算属性
  const moduleStats = computed(() => {
    const totalModules = modules.value.length
    const loadedCount = loadedModules.value.length
    const enabledCount = enabledModules.value.length
    const loadingCount = loadingModules.value.size
    const errorCount = errorModules.value.size

    return {
      total: totalModules,
      loaded: loadedCount,
      enabled: enabledCount,
      loading: loadingCount,
      error: errorCount,
      unloaded: totalModules - loadedCount - loadingCount - errorCount,
      loadRate: totalModules > 0 ? (loadedCount / totalModules) * 100 : 0,
      errorRate: totalModules > 0 ? (errorCount / totalModules) * 100 : 0,
      enableRate: totalModules > 0 ? (enabledCount / totalModules) * 100 : 0
    }
  })

  const modulesByCategory = computed(() => {
    const categories = new Map<string, DynamicModule[]>()
    
    modules.value.forEach(module => {
      const category = module.category || 'default'
      if (!categories.has(category)) {
        categories.set(category, [])
      }
      categories.get(category)!.push(module)
    })
    
    return categories
  })

  const availableCategories = computed(() => {
    return Array.from(modulesByCategory.value.keys()).sort()
  })

  // 核心方法
  async function fetchAvailableModules(): Promise<void> {
    try {
      const response = await fetch('/api/widgets/')
      const data = await response.json()
      
      const dynamicModules: DynamicModule[] = data.widgets.map((widget: any) => ({
        id: widget.id.toString(),
        name: widget.name,
        version: widget.version,
        description: widget.description,
        category: widget.category,
        author: widget.author_name || 'System',
        entry: 'index.vue',
        permissions: [],
        config_schema: widget.config_schema,
        frontend_files: widget.frontend_files,
        is_active: widget.is_active,
        created_at: widget.created_at,
        updated_at: widget.updated_at
      }))

      modules.value = dynamicModules

      for (const module of dynamicModules) {
        await moduleManager.registerModule(module, {
          autoLoadDependencies: false,
          preload: false
        })
      }

      console.log(`[ModuleStore] Fetched ${dynamicModules.length} available modules`)
    } catch (error) {
      console.error('Failed to fetch available modules:', error)
      throw error
    }
  }

  async function loadModule(moduleId: string): Promise<any> {
    if (loadingModules.value.has(moduleId)) {
      throw new Error(`Module ${moduleId} is already loading`)
    }

    loadingModules.value.add(moduleId)
    errorModules.value.delete(moduleId)

    try {
      const component = await moduleManager.loadModule(moduleId)
      
      loadingModules.value.delete(moduleId)
      
      const module = modules.value.find(m => m.id === moduleId)
      if (module && !loadedModules.value.some(m => m.id === moduleId)) {
        loadedModules.value.push(module)
      }

      console.log(`[ModuleStore] Module ${moduleId} loaded successfully`)
      return component
    } catch (error) {
      loadingModules.value.delete(moduleId)
      const errorMessage = error instanceof Error ? error.message : 'Unknown error'
      errorModules.value.set(moduleId, errorMessage)
      
      console.error(`[ModuleStore] Failed to load module ${moduleId}:`, error)
      throw error
    }
  }

  async function unloadModule(moduleId: string): Promise<void> {
    try {
      await moduleManager.unloadModule(moduleId)
      
      loadedModules.value = loadedModules.value.filter(m => m.id !== moduleId)
      errorModules.value.delete(moduleId)
      
      console.log(`[ModuleStore] Module ${moduleId} unloaded successfully`)
    } catch (error) {
      console.error(`[ModuleStore] Failed to unload module ${moduleId}:`, error)
      throw error
    }
  }

  async function reloadModule(moduleId: string): Promise<any> {
    await unloadModule(moduleId)
    return await loadModule(moduleId)
  }

  async function enableModule(moduleId: string): Promise<void> {
    const module = modules.value.find(m => m.id === moduleId)
    if (!module) {
      throw new Error(`Module ${moduleId} not found`)
    }

    if (!enabledModules.value.some(m => m.id === moduleId)) {
      enabledModules.value.push(module)
    }

    if (!isModuleLoaded(moduleId)) {
      await loadModule(moduleId).catch(error => {
        console.error(`Failed to auto-load enabled module ${moduleId}:`, error)
      })
    }

    console.log(`[ModuleStore] Module ${moduleId} enabled`)
  }

  async function disableModule(moduleId: string): Promise<void> {
    enabledModules.value = enabledModules.value.filter(m => m.id !== moduleId)
    
    if (isModuleLoaded(moduleId)) {
      await unloadModule(moduleId)
    }

    console.log(`[ModuleStore] Module ${moduleId} disabled`)
  }

  async function loadModules(moduleIds: string[]): Promise<void> {
    const loadPromises = moduleIds.map(moduleId => 
      loadModule(moduleId).catch(error => {
        console.error(`Failed to load module ${moduleId}:`, error)
      })
    )

    await Promise.all(loadPromises)
  }

  async function unloadModules(moduleIds: string[]): Promise<void> {
    const unloadPromises = moduleIds.map(moduleId => 
      unloadModule(moduleId).catch(error => {
        console.error(`Failed to unload module ${moduleId}:`, error)
      })
    )

    await Promise.all(unloadPromises)
  }

  // 查询方法
  function getModule(moduleId: string): DynamicModule | undefined {
    return modules.value.find(m => m.id === moduleId)
  }

  function isModuleLoaded(moduleId: string): boolean {
    return loadedModules.value.some(m => m.id === moduleId)
  }

  function isModuleEnabled(moduleId: string): boolean {
    return enabledModules.value.some(m => m.id === moduleId)
  }

  function getModuleLoadState(moduleId: string): 'loading' | 'loaded' | 'error' | 'unloaded' {
    if (loadingModules.value.has(moduleId)) return 'loading'
    if (errorModules.value.has(moduleId)) return 'error'
    if (isModuleLoaded(moduleId)) return 'loaded'
    return 'unloaded'
  }

  function getModuleError(moduleId: string): string | undefined {
    return errorModules.value.get(moduleId)
  }

  function getModulePerformanceMetrics(moduleId: string): ModulePerformanceMetrics | undefined {
    return moduleManager.getPerformanceMetrics(moduleId)
  }

  function getModuleErrorHistory(moduleId: string): ModuleErrorInfo[] {
    return moduleManager.getErrorHistory(moduleId)
  }

  function getModuleConfig(moduleId: string): ModuleConfig {
    return moduleConfigs.value.get(moduleId) || {}
  }

  function setModuleConfig(moduleId: string, config: ModuleConfig): void {
    moduleConfigs.value.set(moduleId, config)
  }

  function updateModuleConfig(moduleId: string, config: Partial<ModuleConfig>): void {
    const currentConfig = getModuleConfig(moduleId)
    const newConfig = { ...currentConfig, ...config }
    setModuleConfig(moduleId, newConfig)
  }

  function deleteModuleConfig(moduleId: string): void {
    moduleConfigs.value.delete(moduleId)
  }

  // 搜索和筛选方法
  function searchModules(query: string): DynamicModule[] {
    const lowercaseQuery = query.toLowerCase()
    return modules.value.filter(module => 
      module.name.toLowerCase().includes(lowercaseQuery) ||
      module.description.toLowerCase().includes(lowercaseQuery) ||
      module.category.toLowerCase().includes(lowercaseQuery)
    )
  }

  function getModulesByCategory(category: string): DynamicModule[] {
    return modules.value.filter(module => module.category === category)
  }

  function getModulesWithFrontend(): DynamicModule[] {
    return modules.value.filter(module => module.frontend_files && module.frontend_files.length > 0)
  }

  function getEnabledModulesWithFrontend(): DynamicModule[] {
    return enabledModules.value.filter(module => module.frontend_files && module.frontend_files.length > 0)
  }

  // 系统方法
  function getSystemStats() {
    return moduleManager.getSystemStats()
  }

  async function cleanup(): Promise<void> {
    await moduleManager.cleanup()
    errorModules.value.clear()
    performanceMetrics.value.clear()
    errorHistory.value.clear()
  }

  function reset(): void {
    modules.value = []
    loadedModules.value = []
    enabledModules.value = []
    loadingModules.value.clear()
    errorModules.value.clear()
    performanceMetrics.value.clear()
    errorHistory.value.clear()
    moduleConfigs.value.clear()
  }

  // 事件处理器
  function handleModuleLoaded(moduleId: string): void {
    loadingModules.value.delete(moduleId)
    errorModules.value.delete(moduleId)
    
    const module = modules.value.find(m => m.id === moduleId)
    if (module && !loadedModules.value.some(m => m.id === moduleId)) {
      loadedModules.value.push(module)
    }
    
    console.log(`[ModuleStore] Module ${moduleId} loaded event handled`)
  }

  function handleModuleError(moduleId: string, error: Error): void {
    loadingModules.value.delete(moduleId)
    errorModules.value.set(moduleId, error.message)
    
    console.log(`[ModuleStore] Module ${moduleId} error event handled`)
  }

  function handleModuleUnloaded(moduleId: string): void {
    loadedModules.value = loadedModules.value.filter(m => m.id !== moduleId)
    errorModules.value.delete(moduleId)
    
    console.log(`[ModuleStore] Module ${moduleId} unloaded event handled`)
  }

  // 初始化
  async function initialize(): Promise<void> {
    try {
      await fetchAvailableModules()
      
      moduleManager.on('module:loaded', handleModuleLoaded)
      moduleManager.on('module:error', handleModuleError)
      moduleManager.on('module:unloaded', handleModuleUnloaded)
      
      console.log('[ModuleStore] Module store initialized successfully')
    } catch (error) {
      console.error('[ModuleStore] Failed to initialize module store:', error)
      throw error
    }
  }

  // 返回状态和方法
  return {
    // 状态
    modules,
    loadedModules,
    enabledModules,
    loadingModules,
    errorModules,
    performanceMetrics,
    errorHistory,
    moduleConfigs,
    
    // 计算属性
    moduleStats,
    modulesByCategory,
    availableCategories,
    
    // 核心方法
    fetchAvailableModules,
    loadModule,
    unloadModule,
    reloadModule,
    enableModule,
    disableModule,
    loadModules,
    unloadModules,
    
    // 查询方法
    getModule,
    isModuleLoaded,
    isModuleEnabled,
    getModuleLoadState,
    getModuleError,
    getModulePerformanceMetrics,
    getModuleErrorHistory,
    getModuleConfig,
    setModuleConfig,
    updateModuleConfig,
    deleteModuleConfig,
    
    // 搜索和筛选方法
    searchModules,
    getModulesByCategory,
    getModulesWithFrontend,
    getEnabledModulesWithFrontend,
    
    // 系统方法
    getSystemStats,
    cleanup,
    reset,
    initialize
  }
})
